/**
 * 
 * @authors Your Name (you@example.org)
 * @date    2018-08-30 10:28:46
 * @version $Id$
 */
var express = require("express");
var fs = require('fs');
var router = express.Router();
var db = require('../db/mysql');
var sql = require('../db/sql');
// 初始化Client
var co = require('co');
var OSS = require('ali-oss');
var client = new OSS({
	region: 'oss-cn-beijing',
	accessKeyId: 'LTAIv5iUNFsM1Q9U',
	accessKeySecret: '1OGyfEOgTMt9Sk47We3pU8SC2GFpIw',
	bucket: 'images-funcode'
});

var ali_oss = {
	bucket: 'images-funcode',//oss文件夹名称
	endPoint: 'oss-cn-beijing.aliyuncs.com',
}


// 用户注册
router.post('/reguser', function (req, res, next) {

	let userdata = req.body;
	let that = res;
	let nowdata = Date.parse(new Date());

	db.query('select u.userName userName from user u WHERE u.userName="' + userdata.userName + '"', function (err, reues) {
		if (err) {
			console.log(err);
		} else if (reues.length > 0) {
			that.json("用户名已被使用！")
		} else {
			db.query("INSERT INTO `video_db`.`user` (`id`, `userName`, `paw`,`Email`, `regDate`) VALUES ('', '" + userdata.userName + "', '" + userdata.paw + "', '" + userdata.Email + "', " + nowdata + ")",
				function (err, res) {
					if (err) {
						console.log(err)
					} else {
						let data = {
							code: 0,
							data: [],
							msg: "注册成功"
						}
						that.json(data);
					}
				})
		}
	});
});

//用户登录
router.post('/loginuser', function (req, res, next) {
	let username = req.body.username;
	let userpaw = req.body.userpaw;
	db.query('select u.id id, u.userName userName, u.paw paw, u.Email Email, u.regDate regDate from user u WHERE u.userName="' + username + '" and u.paw="' + userpaw + '"', function (err, reues) {
		if (err) {
			return console.log(err);
		}
		if (reues.length > 0) {
			req.session.user = reues[0];
			console.log("已登录", req.session.user)
			let data = {
				code: 0,
				msg: "登录成功"
			}
			res.json(data);
		} else {
			let data = {
				code: -1,
				msg: "用户名或密码错误！"
			}
			res.json(data);
		}
	});
});

// 返回用户的信息
router.get('/getuserinfo', function (req, res, next) {
	if (!req.session.user) {
		let getusererr = {
			code: -1,
			msg: "你还没登录哟",
			data: ""
		}
		res.json(getusererr);
		return
	}
	console.log(req.url);
	let userdata = {
		code: 0,
		msg: "获取成功",
		data: [req.session.user]
	}
	res.json(userdata);
});

router.post('/logoutLogin', function (req, res, next) {
	console.log(req.url);
	req.session.destroy();
	if (!req.session) {
		let data = {
			code: 0,
			msg: "操作成功",
			data: ""
		}
		res.json(data);
	} else {
		let data = {
			code: -1,
			msg: "退出失败",
			data: ""
		}
		res.json(data);
	}
})

router.post('/addimgfile', function (req, res, next) {
	// 图片数据流
	var imgData = req.body.imgfiles;
	// 构建图片名
	var fileName = Date.now() + '.png';
	// 构建图片路径
	var filePath = fileName;
	//过滤data:URL
	var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
	var dataBuffer = new Buffer(base64Data, 'base64');

	fs.writeFile(filePath, dataBuffer, function (err) {
		if (err) {
			res.end(JSON.stringify({ status: '102', msg: '文件写入失败' }));
		} else {
			var localFile = filePath;
			var key = fileName;
			// 阿里云 上传文件 
			co(function* () {
				client.useBucket(ali_oss.bucket);
				var result = yield client.put(key, filePath);
				var imageSrc = 'http://images-funcode.oss-cn-beijing.aliyuncs.com/' + result.name;
				// 上传之后删除本地文件
				fs.unlinkSync(filePath);
				res.end(JSON.stringify({ status: '200', msg: '上传成功', imageUrl: imageSrc }));
			}).catch(function (err) {
				res.end(JSON.stringify({ status: '101', msg: '上传失败', error: JSON.stringify(err) }));
			});

		}
	});

});





module.exports = router;